// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#pragma once

#include <pollux/exec/container_row_serde.h>
#include <pollux/exec/operator.h>
#include <pollux/exec/row_container.h>
#include <pollux/exec/sort_buffer.h>
#include <pollux/exec/spiller.h>

namespace kumo::pollux::exec {
    /// OrderBy operator implementation: OrderBy stores all its inputs in a
    /// RowContainer as the inputs are added. Until all inputs are available,
    /// it blocks the pipeline. Once all inputs are available, it sorts pointers
    /// to the rows using the RowContainer's compare() function. And finally it
    /// constructs and returns the sorted output RowVector using the data in the
    /// RowContainer.
    /// Limitations:
    /// * It memcopies twice: 1) input to RowContainer and 2) RowContainer to
    /// output.
    class OrderBy : public Operator {
    public:
        OrderBy(
            int32_t operatorId,
            DriverCtx *driverCtx,
            const std::shared_ptr<const core::OrderByNode> &orderByNode);

        bool needsInput() const override {
            return !finished_;
        }

        void addInput(RowVectorPtr input) override;

        void noMoreInput() override;

        RowVectorPtr getOutput() override;

        BlockingReason isBlocked(ContinueFuture * /*future*/) override {
            return BlockingReason::kNotBlocked;
        }

        bool isFinished() override {
            return finished_;
        }

        void reclaim(uint64_t targetBytes, memory::MemoryReclaimer::Stats &stats)
        override;

        void close() override;

    private:
        std::unique_ptr<SortBuffer> sortBuffer_;
        bool finished_ = false;
        vector_size_t maxOutputRows_;
    };
} // namespace kumo::pollux::exec
